'use strict'

const http = require('http')
const Koa = require('koa')
const sendFile = require('koa-sendfile')
const router = require('koa-router')()
const Redis = require('ioredis')
const mongoose = require('mongoose')
const Message = require('./src/models/Message')

mongoose.connect('mongodb://localhost:27017/chatroom')
mongoose.Promise = global.Promise

// 订阅`redis`实例
const redis = new Redis
// 中间的｀redis`实例
// 起到中间的媒介作用
const pub = new Redis

const app = new Koa
// PORT 放到 node 环境变量，方便开启多个实例
const PORT = process.env.PORT || 4003
const CHATROOM = 'chatroom'

redis.subscribe(CHATROOM, (err, count) => {
  // Now we are subscribed to both the 'news' and 'music' channels.
  // `count` represents the number of channels we are currently subscribed to.
})

const server = http.createServer(app.callback())
const io = require('socket.io')(server)

redis.on('message', function (channel, message) {
  const msgObj = JSON.parse(message)
  new Message(msgObj).save()
  io.emit('chat message', msgObj)
})

io.on('connection', (socket) => {
  let message = {
    from: socket.id,
    createdAt: (new Date).toLocaleString(),
  }
  // 新用户
  message.content = 'Welcome the new user.'
  pub.publish(CHATROOM, JSON.stringify(message))

  socket.on('disconnect', () => {
    // 用户断开连接
    message.content = 'The user has gone!'
    pub.publish(CHATROOM, JSON.stringify(message))
  })
  socket.on('chat message', msg => {
    // 用户消息
    message.content = msg
    pub.publish(CHATROOM, JSON.stringify(message))
  })
})

router.get('/', async (ctx, next) => {
  await sendFile(ctx, 'index.html')
})

app.use(router.routes())

server.listen(PORT, () => {
  console.log(`Server is running on :${PORT}`)
})